#!/bin/bash
set -e
export KUBECONFIG=
export CATTLE_DEV_MODE=yes
export CATTLE_SERVER_URL="https://$(ip route get 8.8.8.8 | awk '{print $7}'):443"
export CATTLE_BOOTSTRAP_PASSWORD="admin"
export CATTLE_FEATURES="harvester=false"

cd $(dirname $0)/../

echo "Starting Rancher Server"
entrypoint.sh >./rancher.log 2>&1 &

echo "Waiting for Rancher health check..."
while ! curl -sf http://localhost:80/healthz >/dev/null 2>&1; do
    echo "Waiting for Rancher's /healthz endpoint to become available"
    sleep 2
done

# Tail the rancher logs if rancher fails to deploy the webhook after 5 minutes.
bash -c "sleep 300 && echo 'Rancher has not deployed webhook after 5m tailing logs' && tail -f ./rancher.log" &
# Get PID of the tail command so we can kill it if needed
TAIL_PID=$!

# Wait for Rancher to deploy rancher-webhook.
while ! kubectl rollout status -w -n cattle-system deploy/rancher-webhook >/dev/null 2>&1; do
    echo "Waiting for rancher to deploy rancher-webhook..."
    sleep 2
done

# After rancher deploys webhook kill the bash command running tail.
kill ${TAIL_PID}

###### Upload the newly created webhook image to containerd, then install the webhook chart using the new image
IMAGE_FILE=./dist/rancher-webhook-image.tar
# import image to containerd and get the image name
WEBHOOK_REPO=$(ctr image import ${IMAGE_FILE} | cut -d ' ' -f 2 | cut -d ':' -f 1)

# Source tags file to get the last built tags
source ./dist/tags

# Install the webhook chart we just built.
helm upgrade rancher-webhook ./dist/artifacts/rancher-webhook-${HELM_VERSION}.tgz -n cattle-system --set image.repository=${WEBHOOK_REPO} --set image.tag=${TAG} --reuse-values

while ! kubectl rollout status -w -n cattle-system deploy/rancher-webhook; do
    sleep 2
done

./bin/rancher-webhook-integration.test -test.v -test.run IntegrationTest

# Scale down rancher-webhook so that we can run tests on the FailurePolicy
kubectl scale deploy rancher-webhook -n cattle-system --replicas=0
kubectl wait pods -l app=rancher-webhook --for=delete -n cattle-system
./bin/rancher-webhook-integration.test -test.v -test.run FailurePolicyTest
